<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'

const { required, lengthFix } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => undefined
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const { formRegister, formMethods } = useForm()
const { setValues, setSchema, getFormData, getElFormExpose } = formMethods

const rules: any = reactive({
  name: [required('公司名称不能为空！')],
  tel: [
    required('电话不能为空！'),
    {
      type: 'string',
      message: '手机号长度必须为11位！',
      validator: (rule, value) => value.length == 11
    },
    {
      type: 'string',
      message: '手机号格式不正确！',
      trigger: 'change',
      validator: (rule, value) => /^1[34578]\d{9}$/.test(value)
    }
  ],
  email: [
    required('邮箱不能为空！'),
    {
      type: 'string',
      message: '邮箱格式不正确！',
      trigger: 'change',
      validator: (rule, value) => /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/.test(value)
    }
  ]
})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch(() => {
    // ElMessage.error()
  })

  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

const setContent = async (content: string) => {
  setValues({
    content
  })
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
    setSchema([
      {
        field: 'content',
        path: 'componentProps.defaultHtml',
        value: currentRow.content
      }
    ])
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit,
  setContent
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
